from rest_framework import serializers

from comments.models import Comment
from passages.models import Passage
from subjects.models import Subject
from tag.models import Tags
from tag.serializers import TagsReadOnly
from users.models import UserInfo


class InnerAuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        exclude = ['password', 'created_at', ]


class PassageSerializer(serializers.ModelSerializer):
    tags = TagsReadOnly(many=True, read_only=True)
    active = serializers.BooleanField(read_only=True)
    tag_list = serializers.ListField(write_only=True, required=False)
    author = serializers.SlugRelatedField(
        queryset=UserInfo.objects.all(),
        slug_field='username',
        error_messages={
            "blank": "请输入作者名",
            "required": "请输入作者名"},
        help_text="作者名")
    category = serializers.SlugRelatedField(
        required=False,
        queryset=Subject.objects.all(),
        slug_field='cate_name',
        help_text='学科分类'
    )
    comment = serializers.SerializerMethodField()


    class Meta:
        model = Passage
        fields = '__all__'

    def create(self, validated_data):
        try:
            tags_name = validated_data.pop('tag_list')
        except Exception:
            return super().create(validated_data)
        else:
            passages_instance = super().create(validated_data)
            for name in tags_name:
                tag_instance, _ = Tags.objects.get_or_create(name=name)
                tag_instance.clout += 1
                tag_instance.save()
                passages_instance.tags.add(tag_instance.id)

            return passages_instance

    def get_comment(self, obj):
        comments = Comment.objects.filter(
            passage_id=obj.id).values().order_by('-created_at')
        return comments

    def get_comment_count(self, comments):
        """一级评论数量"""
        cnt = 0
        for comment in comments:
            if not comment['parent_id']:
                cnt += 1
        return cnt

    def to_representation(self, instance):
        res = super().to_representation(instance=instance)
        author = instance.author
        author_ser = InnerAuthorSerializer(author)
        res['author'] = author_ser.data
        return res